home *** CD-ROM | disk | FTP | other *** search
/ The Arsenal Files 8 / The Arsenal Files Collection #8 (Arsenal Computer) (1996).ISO / prg_gen / javnl010.zip / JAVNL010.TXT < prev   
Text File  |  1996-10-03  |  16KB  |  447 lines

  1. Issue #010
  2. October, 1996
  3.  
  4.  
  5. Contents:
  6.  
  7. The Finally Clause and Method Exiting
  8. Comparing C/C++ and Java Part 10 - Labelled Break and Continue
  9. Performance - Garbage Collection and Setting to Null
  10. Newsletter Writing
  11. Introduction to Applet Programming Part 6 - Text Fields
  12.  
  13.  
  14. REVIEWERS NEEDED
  15.  
  16. I am looking for a couple of additional people to help review this
  17. newsletter.  If you are a reviewer, you receive the issue a few days
  18. early, and send me your comments.  The present set of reviewers have
  19. done much to improve the quality of the newsletter.  If you have Java
  20. experience and are interested in this, please send me a note
  21. (glenm@glenmccl.com).
  22.  
  23.  
  24. THE FINALLY CLAUSE AND METHOD EXITING
  25.  
  26. Java has no "goto" statement, though this identifier is reserved in
  27. the language.  There are several ways in which goto is used in C and
  28. C++, and it's interesting to consider the Java alternatives to such
  29. usage.  In this section we will discuss one alternative, and in the
  30. next section another.
  31.  
  32. One way that goto is used is to jump to the end of a function body,
  33. where cleanup can be done.  For example, suppose that we are
  34. manipulating calendar dates, and have a function where we want a year
  35. in the range 1900-99 and evenly divisible by 4.  In C, we might have:
  36.  
  37.         void f(int d)
  38.         {
  39.                 if (d < 1900)
  40.                         goto err;
  41.                 if (d > 1999)
  42.                         goto err;
  43.                 if (d % 4)
  44.                         goto err;
  45.  
  46.                 /* do stuff with date ... */
  47.  
  48.                 return;
  49.  
  50.         err:
  51.                 fprintf(stderr, "invalid date %d\n", d);
  52.         }
  53.  
  54. In Java, we can achieve a similar end without goto, by using a form of
  55. the try-catch-finally statement used in exception handling:
  56.  
  57.         public class test {
  58.  
  59.                 public static void f(int d)
  60.                 {
  61.                         boolean err = true;
  62.  
  63.                         try {
  64.                                 if (d < 1900)
  65.                                         return;
  66.                                 if (d > 1999)
  67.                                         return;
  68.                                 if (d % 4 != 0)
  69.                                         return;
  70.                                 err = false;
  71.                                 // do stuff with date ...
  72.                         }
  73.                         finally {
  74.                                 if (err)
  75.                                         System.err.println("invalid date "
  76.                                             + d);
  77.                         }
  78.                 }
  79.  
  80.                 public static void main(String args[])
  81.                 {
  82.                         f(1852);
  83.                         f(1976);
  84.                         f(1989);
  85.                 }
  86.         }
  87.  
  88. The code within the try block is "tried", that is, executed.  After
  89. the execution of this code, the finally block is executed -- no matter
  90. what happens in the try block.  In the example above, we exit the
  91. method (return) for various error conditions, but when the method is
  92. exited, the finally block is executed.  In this way, we can execute a
  93. series of Java statements, and guarantee that no matter what happens
  94. in those statements, some other processing will follow.
  95.  
  96. Whether this programming style is "good" is a matter of opinion.
  97. Saying "return" with the idea that some cleanup will be done by a
  98. finally block could be viewed as a little sneaky or confusing, or
  99. alternatively this might turn out to be a common Java idiom in a few
  100. months or years.  At the least, you might put in a comment like:
  101.  
  102.         if (condition)
  103.                 return;         // proceed to cleanup phase of method
  104.  
  105. If an exception is thrown in a try block, and there is a local catch
  106. block to handle it, the catch block is executed, and then the finally
  107. block.  If there is not a local catch block, the finally block is
  108. executed, and then the exception is propagated to the nearest catch
  109. block that can handle the exception (that is, the stack is unwound, as
  110. in other exception processing).
  111.  
  112. We will say more about Java exception handling at some future point.
  113.  
  114.  
  115. COMPARING C/C++ AND JAVA PART 10 - LABELLED BREAK AND CONTINUE
  116.  
  117. In C and C++, the break and continue statements are used to break out
  118. of and continue with the next iteration of loops, for example while or
  119. for loops.  break is also used in switch statements.
  120.  
  121. Such breaking and continuing apply only to the enclosing loop.
  122. Sometimes you'd like more flexibility, for example the ability to
  123. break out two levels.  In C, you might say:
  124.  
  125.                 for (i = 1; i <= 10; i++) {
  126.                         for (j = 1; j <= 10; j++) {
  127.                                 if (some condition)
  128.                                         goto done;
  129.                                 /* other processing in loop */
  130.                         }
  131.                 }
  132.         done:
  133.                 /* other processing */
  134.  
  135. This effect could also be achieved by breaking out of the inner loop,
  136. and then testing some program state variable, and then breaking out of
  137. the outer loop.
  138.  
  139. In Java, there's a simpler approach to solving this problem.  The
  140. above could be written as:
  141.  
  142.         outer_block:
  143.                 for (i = 1; i <= 10; i++) {
  144.                         for (j = 1; j <= 10; j++) {
  145.                                 if (some condition)
  146.                                         break outer_block;
  147.                                 // other processing in loop
  148.                         }
  149.                 }
  150.                 // control comes here when break is executed
  151.  
  152. The break statement has a label.  When the statement is executed,
  153. control transfers out of the enclosed labelled statement.  Control is
  154. NOT transferred to the label, but to a point past the end of the
  155. labelled statement.  A labelled continue statement works in a similar
  156. way;  control is transferred to the end of a labelled loop.
  157.  
  158. Note that with both break and continue, any finally block will be
  159. executed before the labelled statement is exited or the next iteration
  160. of a loop takes place.  For example:
  161.  
  162.         loop:
  163.                 while (some condition) {
  164.                         try {
  165.                                 if (some condition)
  166.                                         continue loop;
  167.                                 // other processing
  168.                         }
  169.                         finally {
  170.                                 // some processing
  171.                         }
  172.                 }
  173.  
  174. The labelled continue statement will cause the finally block to be
  175. executed before going to the bottom of the while loop in preparation
  176. for the next iteration of the loop.
  177.  
  178.  
  179. PERFORMANCE - GARBAGE COLLECTION AND SETTING TO NULL
  180.  
  181. In issue #001 we talked about Java garbage collection, where the
  182. runtime system automatically reclaims dynamic storage that is no longer
  183. in use.  For example:
  184.  
  185.         public class test {
  186.                 public void f()
  187.                 {
  188.                         char buf[] = new char[1024];
  189.                         // stuff that uses buf
  190.                 }
  191.         }
  192.  
  193. When method f() exits, the space that buf uses is garbage, because
  194. only a local variable in an invalid stack frame references it.  The
  195. runtime system may eventually reclaim the storage.
  196.  
  197. Garbage collection is automatic.  But sometimes there are ways to help
  198. it out.  Consider a case where you are managing a stack of Object
  199. references:
  200.  
  201.         public class Stack {
  202.  
  203.                 private static final int MAXLEN = 10;
  204.  
  205.                 private Object stk[] = new Object[MAXLEN];
  206.  
  207.                 private int stkp = -1;
  208.  
  209.                 // add in logic for error checking, stack growing, etc. ...
  210.  
  211.                 public void push(Object p)
  212.                 {
  213.                         stk[++stkp] = p;
  214.                 }
  215.  
  216.                 public Object pop()
  217.                 {
  218.                         return stk[stkp--];
  219.                 }
  220.         }
  221.  
  222. Consider a case where the stack has two elements on it, and you pop
  223. one of them.  At this point stk[0] will have a valid element in it,
  224. and stk[1] will have the element just popped.  That is, stk[1] will
  225. have a reference to an Object, which could be a reference to anything,
  226. including a large data structure of many thousands of bytes.  In such
  227. a case, this data structure cannot be garbage collected, even though
  228. it may no longer be in use.
  229.  
  230. To remedy this problem, we can rewrite pop() like so:
  231.  
  232.         public Object pop()
  233.         {
  234.                 Object p = stk[stkp];
  235.                 stk[stkp--] = null;
  236.                 return p;
  237.         }
  238.  
  239. We haven't nullified the Object itself, just a no longer valid
  240. reference to it.  The Stack object itself may have a long lifetime,
  241. and rewriting the pop() method in this way helps ensure that garbage
  242. collection can be done in a timely way.
  243.  
  244.  
  245. NEWSLETTER WRITING
  246.  
  247. Would your company find it valuable to have a customized newsletter on
  248. C++ or Java or related topics, similar to this newsletter that you're
  249. reading right now?  If so, please contact me (glenm@glenmccl.com) for
  250. further information.  Custom newsletters can consist of technical
  251. material furnished from outside, internal material with outside
  252. editting, or a combination of the two.
  253.  
  254.  
  255. INTRODUCTION TO APPLET PROGRAMMING PART 6 - TEXT FIELDS
  256.  
  257. In the previous issue we showed how to use low-level character input
  258. within an applet.  In this issue we'll discuss higher-level input
  259. using TextFields.  Consider the following example, an applet that
  260. gathers name and address from a user and writes the data to a local
  261. file:
  262.  
  263.         import java.applet.*;
  264.         import java.awt.*;
  265.         import java.io.*;
  266.         
  267.         public class text4 extends Applet {
  268.         
  269.                 TextField tf1;                  // text fields for address
  270.                 TextField tf2;
  271.                 TextField tf3;
  272.                 Button db;                      // Done button
  273.                 Label lb;                       // Label used as message
  274.                 Color bg = new Color(0xffffff); // background/foreground clrs
  275.                 Color fg = new Color(0x000000);
  276.         
  277.                 public void init()
  278.                 {
  279.                         // set colors
  280.         
  281.                         setForeground(fg);
  282.                         setBackground(bg);
  283.         
  284.                         // create text fields
  285.         
  286.                         tf1 = new TextField(35);
  287.                         tf2 = new TextField(35);
  288.                         tf3 = new TextField(35);
  289.         
  290.                         // create button and label
  291.         
  292.                         db = new Button("Done");
  293.                         lb = new Label();
  294.         
  295.                         // arrange items in window
  296.         
  297.                         setLayout(new GridLayout(4, 2, 10, 10));
  298.                         add(new Label("Name:"));
  299.                         add(tf1);
  300.                         add(new Label("Address #1:"));
  301.                         add(tf2);
  302.                         add(new Label("Address #2:"));
  303.                         add(tf3);
  304.                         add(db);
  305.                         add(lb);
  306.                 }
  307.         
  308.                 private boolean write()
  309.                 {
  310.                         // check input fields
  311.         
  312.                         if (tf1.getText() == null ||
  313.                             tf1.getText().length() == 0)
  314.                                 return false;
  315.                         if (tf2.getText() == null ||
  316.                             tf2.getText().length() == 0)
  317.                                 return false;
  318.                         if (tf3.getText() == null ||
  319.                             tf3.getText().length() == 0)
  320.                                 return false;
  321.         
  322.                         // write out name and address to end of file
  323.         
  324.                         try {
  325.                                 RandomAccessFile raf = new
  326.                                     RandomAccessFile("datafile", "rw");
  327.                                 raf.seek(raf.length());
  328.                                 raf.writeBytes(tf1.getText());
  329.                                 raf.writeByte('\n');
  330.                                 raf.writeBytes(tf2.getText());
  331.                                 raf.writeByte('\n');
  332.                                 raf.writeBytes(tf3.getText());
  333.                                 raf.writeByte('\n');
  334.                                 raf.writeByte('\n');
  335.                                 raf.close();
  336.                         }
  337.                         catch (Throwable e) {
  338.                         }
  339.         
  340.                         return true;
  341.                 }
  342.         
  343.                 public boolean action(Event e, Object o)
  344.                 {
  345.         
  346.                         // Done button selected
  347.         
  348.                         if (e.target == db) {
  349.                                 if (write())
  350.                                         lb.setText("Written ...");
  351.                                 else
  352.                                         lb.setText("Invalid field value");
  353.                                 return true;
  354.                         }
  355.                         else {
  356.                                 return false;
  357.                         }
  358.                 }
  359.         }
  360.  
  361. This applet uses the following HTML code to drive it:
  362.  
  363.         <html>
  364.  
  365.         <body bgcolor="#ffffff" text="#000000" link="#ff0000" vlink="#000000">
  366.  
  367.         <head>
  368.  
  369.         <title>Interface to Text Applet</title>
  370.  
  371.         </head>
  372.  
  373.         <body>
  374.  
  375.         Please enter your name and address then select Done.
  376.         <br>
  377.         <br>
  378.  
  379.         <applet code="text4.class" width=350 height=125></applet>
  380.  
  381.         </body>
  382.  
  383.         </html>
  384.  
  385. In this example, we use the init() method of the applet to set the
  386. background and foreground colors, and then we create the individual
  387. items of the window.  We use a layout manager for this purpose.  A
  388. layout manager is a mechanism for arranging items in a window, or more
  389. precisely, Component objects in a Container.  Applet is derived from
  390. Panel which is derived from Container.  And an item like TextField is
  391. derived from TextComponent which is derived from Component.
  392.  
  393. So when we create text fields and buttons and so on, we are creating
  394. objects of classes derived from Component, and using a layout manager
  395. to arrange these objects in a Container object.
  396.  
  397. After we've set up the window items, we can then add some logic within
  398. the action() method to check whether the user selected the Done
  399. button, and if so, then we interrogate the text fields using getText()
  400. and extract the input data.  Finally, we write this data to a file.
  401. We append to the end of the file by obtaining its length and
  402. positioning at the end of file.
  403.  
  404.  
  405. ACKNOWLEDGEMENTS
  406.  
  407. Thanks to Thierry Ciot, Irv Kanode, and Mike Paluka for help with
  408. proofreading.
  409.  
  410.  
  411. SUBSCRIPTION INFORMATION / BACK ISSUES
  412.  
  413. To subscribe to the newsletter, send mail to majordomo@world.std.com
  414. with this line as its message body:
  415.  
  416. subscribe java_letter
  417.  
  418. Back issues are available via FTP from:
  419.  
  420.         rmi.net /pub2/glenm/javalett
  421.  
  422. or on the Web at:
  423.  
  424.         http://rmi.net/~glenm
  425.  
  426. There is also a C++ newsletter.  To subscribe to it, say:
  427.  
  428. subscribe c_plus_plus
  429.  
  430. using the same majordomo@world.std.com address.
  431.  
  432. -------------------------
  433.  
  434. Copyright (c) 1996 Glen McCluskey.  All Rights Reserved.
  435.  
  436. This newsletter may be further distributed provided that it is copied
  437. in its entirety, including the newsletter number at the top and the
  438. copyright and contact information at the bottom.
  439.  
  440. Glen McCluskey & Associates
  441. Professional Computer Consulting
  442. Internet: glenm@glenmccl.com
  443. Phone: (800) 722-1613 or (970) 490-2462
  444. Fax: (970) 490-2463
  445. FTP: rmi.net /pub2/glenm/javalett (for back issues)
  446. Web: http://rmi.net/~glenm
  447.